package cn.virens.web.controller.admin.system;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageInfo;

import cn.virens.database.mysql.model.sys.SysResource;
import cn.virens.database.service.sys.SysResourceService;
import cn.virens.util.RequestUtil;
import cn.virens.util.page.Page;
import cn.virens.web.common.BaseDataTableController;

/**
 * 资源管理
 * 
 * @作者 : loioi
 * @创建时间 :2017年8月4日 上午11:04:21
 */
@Controller
@RequestMapping("/admin/system/resource")
public class SysResourceContorller extends BaseDataTableController<SysResource, SysResourceService> {

	@Autowired
	public SysResourceContorller(SysResourceService service) {
		super("admin/system/resource/", "system:resource", service);
	}

	@ResponseBody
	@RequestMapping("resources.json")
	public Model getSimpleResource(HttpServletRequest request, Model model) {
		return renderSuccess(baseService.getSimpleResource(null), model);
	}

	@Override
	protected PageInfo<?> getData(HttpServletRequest request, Page page) throws Exception {
		page.addParam("name", RequestUtil.getValueStr(request, "name", null));

		return super.getData(request, page);
	}

	@Override
	protected Model addHandle(HttpServletRequest request, Model model, SysResource record) throws Exception {
		record.setParentCode(RequestUtil.getValueStr(request, "parent", ""));

		return super.addHandle(request, model, record);
	}

	@Override
	protected Model editHandle(HttpServletRequest request, Model model, SysResource record) throws Exception {
		String parent = RequestUtil.getValueStr(request, "parent", "");

		int result1 = 0;
		int result2 = 1;

		// 验证父级资源是否发生改变，如果改变了更新父级引用
		if (!StringUtils.equals(parent, record.getParentCode())) {
			result2 = result2 & baseService.updateParent(record.getCode(), parent);
		}
		// 更新资源信息
		record.setParentCode(parent);
		result1 = baseService.update(record);

		if ((result2 & result1) > 0) {
			return renderSuccess(model, "更新成功");
		} else {
			return renderFail(model, "更新失败");
		}
	}
}
